<?
class Persistable{
	protected $id;

	public function Persistable(){
	}

	public function getId() {
		return $this->id;
	}

	public function setId($id){
		$this->id = $id;
	}

	public function getMapping() {
		// First of all, analyse wich variables do we really need to add
		$vars = $this->mapping;
        
		$obj = $this;

		while(($parent = get_parent_class($obj)) != "Persistable"){
			$obj = new $parent();
			$vars = array_merge($vars, $obj->mapping);
		}
		return $vars;
	}

    static function formatTime($date){
		return date("Y-m-d G:i", $date);
	}

	/**
	 * Rewrite of all the getter and setters method
	 * so you dont have to write them again!
	 */
	function __call($method, $arguments) {
		$prefix = strtolower(substr($method, 0, 3));
		$property = substr($method, 3);

		$map = $this->getMapping();
		if(empty($prefix) || empty($property)) {
			return;
		}
		$property{0} = strtolower($property{0});

		if ($prefix == "get" && isset($map[$property])) {
			$idget = $property."_id";

			if($map[$property]["type"] == "OBJECT"){
				if(isset($this->$property)){
					return $this->$property;
				} else if(!isset($this->$idget) || $this->$idget <= 0){
					return null;
				} else {
					$this->$property = db::get($map[$property]["target"], $this->$idget);
				}
			}
			return $this->$property;
		}

		if ($prefix == "set" && isset($map[$property])) {
			$this->$property = $arguments[0];

			if($map[$property]["type"] == "OBJECT" && isset($this->$property)){
				$idget = $property."_id";
				if($arguments[0] != null){
					$this->$idget = &$arguments[0]->getId();
				}
			}
		}
	}
}
?>